<template>
  <div class="quality-report">
    <div class="page-header">
      <div class="header-left">
        <h2>质量统计</h2>
        <p>质量检测数据统计分析和趋势监控</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="generateReport">
          <el-icon><Document /></el-icon>
          生成报告
        </el-button>
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ qualityStats.totalInspections }}</div>
                <div class="stat-label">总检测数</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ qualityStats.inspectionGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon passed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ qualityStats.passedInspections }}</div>
                <div class="stat-label">合格检测</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ qualityStats.passedGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon failed">
                <el-icon><CircleClose /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ qualityStats.failedInspections }}</div>
                <div class="stat-label">不合格检测</div>
                <div class="stat-trend down">
                  <el-icon><ArrowDown /></el-icon>
                  -{{ qualityStats.failedDecrease }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon rate">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ qualityStats.passRate }}%</div>
                <div class="stat-label">合格率</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ qualityStats.rateGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" inline>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="检测类型">
            <el-select
              v-model="filterForm.inspectionType"
              placeholder="请选择类型"
              clearable
              style="width: 150px"
            >
              <el-option label="常规检测" value="routine" />
              <el-option label="专项检测" value="special" />
              <el-option label="抽检" value="random" />
              <el-option label="复检" value="recheck" />
            </el-select>
          </el-form-item>
          <el-form-item label="检测结果">
            <el-select
              v-model="filterForm.result"
              placeholder="请选择结果"
              clearable
              style="width: 120px"
            >
              <el-option label="合格" value="passed" />
              <el-option label="不合格" value="failed" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select
              v-model="filterForm.categoryId"
              placeholder="请选择分类"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 图表分析 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 合格率趋势 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>合格率趋势</span>
            </template>
            <div ref="passRateChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <!-- 检测类型分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>检测类型分布</span>
            </template>
            <div ref="inspectionTypeChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 不合格原因分析 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>不合格原因分析</span>
            </template>
            <div ref="failureReasonChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <!-- 分类质量对比 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>分类质量对比</span>
            </template>
            <div ref="categoryQualityChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 质量详情表格 -->
    <div class="table-section">
      <el-card>
        <template #header>
          <div class="table-header">
            <span>质量检测记录</span>
            <div class="table-actions">
              <el-button type="primary" size="small" @click="showAddInspection = true">
                <el-icon><Plus /></el-icon>
                新增检测
              </el-button>
              <el-button type="warning" size="small" @click="batchRecheck">
                <el-icon><Refresh /></el-icon>
                批量复检
              </el-button>
            </div>
          </div>
        </template>
        
        <el-table
          :data="qualityList"
          v-loading="tableLoading"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="inspectionCode" label="检测编号" width="120" />
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="category" label="分类" width="100" />
          <el-table-column prop="inspectionType" label="检测类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getInspectionTypeTag(row.inspectionType)">
                {{ getInspectionTypeText(row.inspectionType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="inspector" label="检测员" width="100" />
          <el-table-column prop="inspectionDate" label="检测日期" width="120" />
          <el-table-column prop="passRate" label="合格率" width="100">
            <template #default="{ row }">
              <el-progress
                :percentage="row.passRate"
                :color="getPassRateColor(row.passRate)"
                :stroke-width="8"
              />
            </template>
          </el-table-column>
          <el-table-column prop="result" label="检测结果" width="100">
            <template #default="{ row }">
              <el-tag :type="row.result === 'passed' ? 'success' : 'danger'">
                {{ row.result === 'passed' ? '合格' : '不合格' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewDetail(row)">
                详情
              </el-button>
              <el-button type="warning" size="small" @click="recheck(row)">
                复检
              </el-button>
              <el-button type="info" size="small" @click="editInspection(row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { 
  Document, 
  Download, 
  Search, 
  Refresh, 
  Plus,
  CircleCheck,
  CircleClose,
  TrendCharts,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'

export default defineComponent({
  name: 'QualityReport',
  components: {
    Document,
    Download,
    Search,
    Refresh,
    Plus,
    CircleCheck,
    CircleClose,
    TrendCharts,
    ArrowUp,
    ArrowDown
  },
  setup() {
    const tableLoading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const showAddInspection = ref(false)
    const selectedRecords = ref([])
    
    // 图表引用
    const passRateChart = ref(null)
    const inspectionTypeChart = ref(null)
    const failureReasonChart = ref(null)
    const categoryQualityChart = ref(null)
    
    // 筛选表单
    const filterForm = reactive({
      dateRange: [],
      inspectionType: '',
      result: '',
      categoryId: null
    })
    
    // 质量统计数据
    const qualityStats = reactive({
      totalInspections: 1250,
      inspectionGrowth: 8.5,
      passedInspections: 1180,
      passedGrowth: 9.2,
      failedInspections: 70,
      failedDecrease: 12.5,
      passRate: 94.4,
      rateGrowth: 0.8
    })
    
    // 分类数据
    const categories = ref([
      { id: 1, name: '生鲜食品' },
      { id: 2, name: '饮料酒水' },
      { id: 3, name: '零食糖果' },
      { id: 4, name: '日用品' },
      { id: 5, name: '电子产品' }
    ])
    
    // 质量检测列表数据
    const qualityList = ref([
      {
        inspectionCode: 'QC001',
        productName: '有机苹果',
        category: '生鲜食品',
        inspectionType: 'routine',
        inspector: '张三',
        inspectionDate: '2024-01-15',
        passRate: 95,
        result: 'passed',
        status: 'completed'
      },
      {
        inspectionCode: 'QC002',
        productName: '纯牛奶',
        category: '饮料酒水',
        inspectionType: 'special',
        inspector: '李四',
        inspectionDate: '2024-01-15',
        passRate: 88,
        result: 'passed',
        status: 'completed'
      },
      {
        inspectionCode: 'QC003',
        productName: '面包',
        category: '零食糖果',
        inspectionType: 'random',
        inspector: '王五',
        inspectionDate: '2024-01-14',
        passRate: 65,
        result: 'failed',
        status: 'pending'
      },
      {
        inspectionCode: 'QC004',
        productName: '洗发水',
        category: '日用品',
        inspectionType: 'routine',
        inspector: '赵六',
        inspectionDate: '2024-01-14',
        passRate: 92,
        result: 'passed',
        status: 'completed'
      }
    ])
    
    // 初始化图表
    const initCharts = () => {
      nextTick(() => {
        // 合格率趋势图
        const passRate = echarts.init(passRateChart.value)
        passRate.setOption({
          title: { text: '近30天合格率趋势' },
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: 'category',
            data: ['1月1日', '1月5日', '1月10日', '1月15日', '1月20日', '1月25日', '1月30日']
          },
          yAxis: { 
            type: 'value',
            min: 80,
            max: 100
          },
          series: [{
            data: [92, 93, 94, 94.4, 95, 94.5, 94.4],
            type: 'line',
            smooth: true,
            areaStyle: {}
          }]
        })
        
        // 检测类型分布
        const inspectionType = echarts.init(inspectionTypeChart.value)
        inspectionType.setOption({
          title: { text: '检测类型分布' },
          tooltip: { trigger: 'item' },
          series: [{
            type: 'pie',
            radius: '50%',
            data: [
              { value: 600, name: '常规检测' },
              { value: 300, name: '专项检测' },
              { value: 250, name: '抽检' },
              { value: 100, name: '复检' }
            ]
          }]
        })
        
        // 不合格原因分析
        const failureReason = echarts.init(failureReasonChart.value)
        failureReason.setOption({
          title: { text: '不合格原因分析' },
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: ['农药残留', '重金属超标', '细菌超标', '包装破损', '其他'] },
          yAxis: { type: 'value' },
          series: [{
            data: [25, 20, 15, 8, 2],
            type: 'bar',
            itemStyle: { color: '#F56C6C' }
          }]
        })
        
        // 分类质量对比
        const categoryQuality = echarts.init(categoryQualityChart.value)
        categoryQuality.setOption({
          title: { text: '分类质量对比' },
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: ['生鲜食品', '饮料酒水', '零食糖果', '日用品', '电子产品'] },
          yAxis: { 
            type: 'value',
            min: 80,
            max: 100
          },
          series: [{
            data: [95, 92, 88, 96, 94],
            type: 'bar',
            itemStyle: { color: '#67C23A' }
          }]
        })
      })
    }
    
    // 筛选处理
    const handleFilter = () => {
      currentPage.value = 1
      loadData()
    }
    
    // 重置筛选
    const resetFilter = () => {
      Object.assign(filterForm, {
        dateRange: [],
        inspectionType: '',
        result: '',
        categoryId: null
      })
      currentPage.value = 1
      loadData()
    }
    
    // 加载数据
    const loadData = async () => {
      tableLoading.value = true
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        total.value = qualityList.value.length
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
                  tableLoading.value = true
      }
    }
    
    // 生成报告
    const generateReport = async () => {
      try {
        ElMessage.success('质量报告生成成功')
      } catch (error) {
        console.error('生成报告失败:', error)
        ElMessage.error('生成报告失败')
      }
    }
    
    // 导出数据
    const exportData = async () => {
      try {
        ElMessage.success('数据导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }
    
    // 查看详情
    const viewDetail = (row) => {
      ElMessage.info(`查看检测详情: ${row.inspectionCode}`)
    }
    
    // 复检
    const recheck = (row) => {
      ElMessageBox.confirm(
        `确定要对检测记录 ${row.inspectionCode} 进行复检吗？`,
        '确认复检',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        ElMessage.success('复检任务已创建')
      }).catch(() => {
        // 用户取消
      })
    }
    
    // 编辑检测
    const editInspection = (row) => {
      ElMessage.info(`编辑检测记录: ${row.inspectionCode}`)
    }
    
    // 批量复检
    const batchRecheck = () => {
      if (selectedRecords.value.length === 0) {
        ElMessage.warning('请选择要复检的记录')
        return
      }
      
      ElMessageBox.confirm(
        `确定要对选中的 ${selectedRecords.value.length} 条记录进行批量复检吗？`,
        '确认批量复检',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        ElMessage.success('批量复检任务已创建')
      }).catch(() => {
        // 用户取消
      })
    }
    
    // 选择变化
    const handleSelectionChange = (selection) => {
      selectedRecords.value = selection
    }
    
    // 获取检测类型标签
    const getInspectionTypeTag = (type) => {
      const tagMap = {
        'routine': 'primary',
        'special': 'success',
        'random': 'warning',
        'recheck': 'info'
      }
      return tagMap[type] || 'info'
    }
    
    // 获取检测类型文本
    const getInspectionTypeText = (type) => {
      const textMap = {
        'routine': '常规检测',
        'special': '专项检测',
        'random': '抽检',
        'recheck': '复检'
      }
      return textMap[type] || '未知'
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'pending': 'warning',
        'completed': 'success',
        'cancelled': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待处理',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知'
    }
    
    // 获取合格率颜色
    const getPassRateColor = (rate) => {
      if (rate >= 90) return '#67C23A'
      if (rate >= 80) return '#E6A23C'
      return '#F56C6C'
    }
    
    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadData()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadData()
    }
    
    onMounted(() => {
      loadData()
      initCharts()
    })
    
    return {
      tableLoading,
      currentPage,
      pageSize,
      total,
      showAddInspection,
      selectedRecords,
      passRateChart,
      inspectionTypeChart,
      failureReasonChart,
      categoryQualityChart,
      filterForm,
      qualityStats,
      categories,
      qualityList,
      handleFilter,
      resetFilter,
      loadData,
      generateReport,
      exportData,
      viewDetail,
      recheck,
      editInspection,
      batchRecheck,
      handleSelectionChange,
      getInspectionTypeTag,
      getInspectionTypeText,
      getStatusType,
      getStatusText,
      getPassRateColor,
      handleSizeChange,
      handleCurrentChange
    }
  }
})
</script>

<style scoped>
.quality-report {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #2563eb;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      &.total {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }
      
      &.passed {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        color: white;
      }
      
      &.failed {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        color: white;
      }
      
      &.rate {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        color: white;
      }
      
      .el-icon {
        font-size: 24px;
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 4px;
      }
      
      .stat-trend {
        font-size: 12px;
        display: flex;
        align-items: center;
        
        &.up {
          color: #67C23A;
        }
        
        &.down {
          color: #F56C6C;
        }
        
        .el-icon {
          margin-right: 2px;
        }
      }
    }
  }
}

.filter-section {
  margin-bottom: 20px;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  .chart-container {
    height: 300px;
  }
}

.table-section {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .table-actions {
    display: flex;
    gap: 10px;
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .stats-overview {
    .el-col {
      margin-bottom: 20px;
    }
  }
  
  .charts-section {
    .el-col {
      margin-bottom: 20px;
    }
  }
}
</style> 